package me.youline.dataServer.service;

import me.youline.dataServer.dao.SocialLatestNotificationRecordDAO;
import me.youline.dataServer.entity.socialActionMsg.MsgNotifyLatestRecord;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LatestNotifyRecordService {
	
	@Autowired
	private SocialLatestNotificationRecordDAO latestDAO;
	
	/**
	 * 获取最新通知记录
	 * @param userId
	 * @return
	 */
	@Transactional
	public MsgNotifyLatestRecord  getMsgNotifyLatestRecord(Long userId){
		MsgNotifyLatestRecord r = latestDAO.getRecordByUserId(userId);
		if(r == null){
			latestDAO.addUserSocialNotificationRecord(userId);
			r = new MsgNotifyLatestRecord();
			r.setExistsNewNotice(false);
			r.setUserId(userId);
			r.setLatestNoticeId(null);
			r.setUnReadTotal(0);
		}
		return r;
	}
	
	/**
	 * 判断是否存在最新消息
	 * @param userId
	 * @return
	 */
	@Transactional
	public boolean isExistLatestMsg(Long userId){
		return this.getMsgNotifyLatestRecord(userId).isExistsNewNotice();
	}
	
	/**
	 * 重置最新消息记录，即将未读数置0，同时将标志位设置为false
	 * @param userId
	 */
	@Transactional
	public void resetLatestMsgRecord(Long userId){
		latestDAO.resetUserNotificationRecord(userId);
	}
	
	/**
	 * 根据用户id获取其未读的最新消息数
	 * @param userId
	 * @return
	 */
	public int getUnReadTotal(Long userId){
		return latestDAO.getUnReadTotalNum(userId);
	}
	
	/**
	 * 设置最新通知记录
	 * @param userId
	 * @param msgId
	 */
	public void setAsLatestRecord(Long userId,Long msgId){
		int n = latestDAO.setAsLatestNotificationRecord(userId, msgId);
		if( n <= 0 ){
			 this.getMsgNotifyLatestRecord(userId);
		}
	}
	
}
